package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.AvailableEnum;
import cn.huiyunche.base.service.framework.security.Md5PasswordEncoder;
import cn.huiyunche.base.service.interfaces.AdminUserService;
import cn.huiyunche.base.service.mappers.SysAdminRoleUserMapper;
import cn.huiyunche.base.service.mappers.SysAdminUserMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.SysAdminUserVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminUserServiceImpl.class);

    @Autowired
    private SysAdminUserMapper sysAdminUserMapper = null;

    @Autowired
    private RoleServiceImpl roleServiceImpl = null;

    @Autowired
    private SysAdminRoleUserMapper sysAdminRoleUserMapper = null;

    @Override
    public SysAdminUser sign(String userName, String password) {
        LOGGER.info("sign params {}, {}", userName, password);
        if (StringUtils.isBlank(userName)) {
            LOGGER.info("sign username is not null");
            throw new IllegalArgumentException("用户名不能为空");
        } else if (StringUtils.isBlank(password)) {
            LOGGER.info("sign password is not null");
            throw new IllegalArgumentException("密码不能为空");
        }
        SysAdminUserExample search = new SysAdminUserExample();
        SysAdminUserExample.Criteria criteria = search.createCriteria();
        criteria.andUsernameEqualTo(userName);
        List<SysAdminUser> users = new ArrayList<SysAdminUser>();
        try {
            users = this.getSysAdminUserMapper().selectByExample(search);
        } catch (Exception e) {
            LOGGER.error("select User error : {}", e);
            throw new IllegalArgumentException("查询用户失败");
        }
        if (CollectionUtils.isEmpty(users) && users.size() == 0) {
            LOGGER.info("The current user does not exist");
            throw new IllegalArgumentException("此用户不存在");
        }
        SysAdminUser user = users.get(0);
        if (!user.getPassword().equals(password)) {
            LOGGER.info("The user name or password error");
            throw new IllegalArgumentException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public SysAdminUser getThisUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails ud = (UserDetails) authentication.getPrincipal();
        if (null != ud) {
            SysAdminUserExample saue = new SysAdminUserExample();
            saue.createCriteria().andUsernameEqualTo(ud.getUsername()).andEnabledEqualTo(AvailableEnum.T.getValue());
            List<SysAdminUser> list = this.getSysAdminUserMapper().selectByExample(saue);
            return list.size() > 0 ? list.get(0) : null;
        }
        return null;
    }

    @Override
    public Result<List<SysAdminUserVo>> all() {
        Result<List<SysAdminUserVo>> r = new Result<>(true);
        List<SysAdminUser> list = this.getSysAdminUserMapper().selectByExample(null);
        List<SysAdminUserVo> listV = new ArrayList<>();
        for (SysAdminUser sau : list) {
            SysAdminUserVo sauv = new SysAdminUserVo();
            BeanCopier beanCopierT = BeanCopier.create(SysAdminUser.class, SysAdminUserVo.class, false);
            beanCopierT.copy(sau, sauv, null);
            SysAdminRole sar = this.getRoleServiceImpl().getUserRole(sau.getId());
            if (null != sar) {
                sauv.setRoleId(sar.getId());
                sauv.setRoleName(sar.getName());
            }
            // 密码不显示
            sauv.setPassword(null);
            sauv.setNewPassword(null);
            listV.add(sauv);
        }
        r.setData(listV);
        return r;
    }

    @Override
    public Result<String> save(SysAdminUserVo sauv) {
        LOGGER.info("save param : {}", sauv);
        Result<String> r = new Result<>(false);
        Long id = sauv.getId();
        String userName = sauv.getUsername();
        if (StringUtils.isBlank(userName)) {
            r.setMessage("用户名不可为空");
            return r;
        }
        Long roleId = sauv.getRoleId();
        if (null == roleId) {
            r.setMessage("请指定用户角色");
            return r;
        }
        // 添加
        if (null == id) {
            // 检查用户是否存在
            SysAdminUserExample saue = new SysAdminUserExample();
            saue.createCriteria().andUsernameEqualTo(userName);
            List<SysAdminUser> list = this.getSysAdminUserMapper().selectByExample(saue);
            if (list.size() > 0) {
                r.setMessage("用户已存在");
                return r;
            }
            sauv.setPassword(new Md5PasswordEncoder().encodePassword(sauv.getNewPassword(), null));
            this.getSysAdminUserMapper().insert(sauv);
            // 加入角色
            this.insertRoleUser(sauv.getId(), roleId);
            r.setSuccess(true);
            return r;
        }
        // 修改
        String newPassword = sauv.getNewPassword();
        if (StringUtils.isNotBlank(newPassword)) {
            sauv.setPassword(new Md5PasswordEncoder().encodePassword(newPassword, null));
        }
        SysAdminUser sauBean = this.getSysAdminUserMapper().selectByPrimaryKey(id);
        sauv.setUsername(sauBean.getUsername());
        this.getSysAdminUserMapper().updateByPrimaryKeySelective(sauv);
        // 删除用户角色
        this.removeRoleUser(id, roleId);
        // 加入角色
        this.insertRoleUser(id, roleId);
        r.setSuccess(true);
        return r;
    }

    @Override
    public Result<String> remove(Long id) {
        LOGGER.info("remove param : {}", id);
        Result<String> r = new Result<>(false);
        if (null == id) {
            r.setMessage("该条记录不存在");
            return r;
        }
        this.getSysAdminUserMapper().deleteByPrimaryKey(id);
        r.setSuccess(true);
        return r;
    }

    @Override
    public Result<SysAdminUserVo> byId(Long id) {
        LOGGER.info("remove byId : {}", id);
        Result<SysAdminUserVo> r = new Result<>(false);
        if (null == id) {
            r.setMessage("该条记录不存在");
            return r;
        }
        SysAdminUser sau = this.getSysAdminUserMapper().selectByPrimaryKey(id);
        SysAdminUserVo sauv = new SysAdminUserVo();
        BeanCopier beanCopierT = BeanCopier.create(SysAdminUser.class, SysAdminUserVo.class, false);
        beanCopierT.copy(sau, sauv, null);
        SysAdminRole sar = this.getRoleServiceImpl().getUserRole(sau.getId());
        if (null != sar) {
            sauv.setRoleId(sar.getId());
            sauv.setRoleName(sar.getName());
        }
        // 密码不显示
        sauv.setPassword(null);
        sauv.setNewPassword(null);
        r.setSuccess(true);
        r.setData(sauv);
        return r;
    }

    /**
     * 插入用户角色
     *
     * @param userId
     * @param roleId
     */
    private void insertRoleUser(Long userId, Long roleId) {
        LOGGER.info("insertRoleUser params : {}, {}", userId, roleId);
        SysAdminRoleUser saru = new SysAdminRoleUser();
        saru.setRoleId(roleId);
        saru.setUserId(userId);
        this.getSysAdminRoleUserMapper().insert(saru);
    }

    /**
     * 删除用户角色
     *
     * @param userId
     * @param roleId
     */
    private void removeRoleUser(Long userId, Long roleId) {
        LOGGER.info("insertRoleUser params : {}, {}", userId, roleId);
        SysAdminRoleUserExample sarue = new SysAdminRoleUserExample();
        sarue.createCriteria().andUserIdEqualTo(userId);
        this.getSysAdminRoleUserMapper().deleteByExample(sarue);
    }

    private SysAdminUserMapper getSysAdminUserMapper() {
        return this.sysAdminUserMapper;
    }

    private RoleServiceImpl getRoleServiceImpl() {
        return this.roleServiceImpl;
    }

    private SysAdminRoleUserMapper getSysAdminRoleUserMapper() {
        return this.sysAdminRoleUserMapper;
    }

}
